package com.javaweb.context;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * ApplicationContextHelper
 * @see new ClassPathXmlApplicationContext(xmlFilePath).getBean(beanName)
 * @see WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getBean(beanName)
 * @author tank2140896
 */
public class ApplicationContextHelper implements ApplicationContextAware { 
	
	/**
	 * ApplicationContext
	 */
    private static ApplicationContext applicationContext;  
    
    /**
     * 将ApplicationContext赋值给ApplicationContextHelper.applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    	ApplicationContextHelper.applicationContext = applicationContext;    
    }  

    /**
     * 获取ApplicationContext
     * <p>
     * AbstractRoutingDataSource abstractRoutingDataSource = (AbstractRoutingDataSource) ApplicationContextHelper.getApplicationContext().getBean("multipleDataSourceManage");
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {  
        return applicationContext;  
    }  
   
    /**
     * 根据bean名称获取bean对象
     * @param beanName bean名称
     * @return Object bean对象
     */
    public static Object getBean(String beanName) {    
        return applicationContext.getBean(beanName);    
    }
    
    /**
     * 根据接口获取接口实现
     * <P>
     * 使用示例：
     * @Component
	 * public class IdGenerator implements IdentifierGenerator {
	 *     public Long nextId(Object entity) {
	 *         return SecretUtil.defaultGenPkNumForLong(String.valueOf(SystemConstant.SYSTEM_NO));
	 *     }
	 * }
     * Map<String,IdentifierGenerator> map = applicationContext.getBeansOfType(IdentifierGenerator.class);
     * IdentifierGenerator ig = map.get("idGenerator");
     * System.out.println(ig.nextId(null));
     * 或
     * ServiceLoader<IdentifierGenerator> loader = ServiceLoader.load(IdentifierGenerator.class);
     * System.out.println(loader);
     * <P>    
     * @param interfaceClass 接口类
     * @return Map<String,? extends T> 接口实现
     */
    public static <T> Map<String,? extends T> getInterfaceImpl(Class<T> interfaceClass) {
    	return applicationContext.getBeansOfType(interfaceClass);
    }
    
}   
